//
//  AppDelegate.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/21.
//  Copyright © 2018 KK. All rights reserved.
//

#import "AppDelegate.h"

#import <UserNotifications/UserNotifications.h>

#import "KKNetworkRequest+V1.h"
#import "KKConversationManager.h"

#import "KKLoginViewController.h"
#import "KKChatListTableViewController.h"
#import "KKNavigationController.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@property (nonatomic, strong) NSData *deviceToken;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions: (UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"注册推送成功！");
        }
    }];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    
    [KKUser synchronizationReadData];
    if (![KKUser isLogin]) {
        [self setLoginViewController];
    }
    else {
        [self setChatListViewController];
    }
    
    [self private_listenUserStatus];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    application.applicationIconBadgeNumber = 0;
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark 推送相关

// 此方法是必须要有实现，否则SDK将无法处理应用注册的Token，推送也就不会成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"push....%@",[deviceToken pushToken]);
    self.deviceToken = deviceToken;
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"error....%@",error);
}


/**
 收到静默推送的回调
 
 @param application  UIApplication 实例
 @param userInfo 推送时指定的参数
 @param completionHandler 完成回调
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [KKConversationManager receiveNewMessage: userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - UNUserNotificationCenterDelegate methods
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
    
    [KKConversationManager receiveNewMessage: response.notification.request.content.userInfo];
    completionHandler();
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    //  接收到了新的推送消息
    [KKConversationManager receiveNewMessage: notification.request.content.userInfo];
    
    completionHandler(UNNotificationPresentationOptionSound);
}


#pragma mark - Private methods
//  监听用户状态
- (void)private_listenUserStatus {
    KKUser.defaultUser.updateBlock = ^(BOOL isLogin) {
        
        if (isLogin) {
            //  登录
            KKNavigationController *mainViewController = [KKNavigationController viewControllerFromSB];
            UIViewController* rootViewController = self.window.rootViewController;
            __weak typeof(self) weakSelf = self;
            [UIView transitionFromView:rootViewController.view toView: mainViewController.view  duration:0.5 options: UIViewAnimationOptionTransitionCrossDissolve completion:^(BOOL finished) {
                weakSelf.window.rootViewController = mainViewController;
                [weakSelf.window makeKeyAndVisible];
            }];
        }
        else {
            //  退出登录
            KKLoginViewController *loginViewController = [KKLoginViewController viewControllerFromSB];
            UIViewController* rootViewController = self.window.rootViewController;
            __weak typeof(self) weakSelf = self;
            [UIView transitionFromView:rootViewController.view toView: loginViewController.view  duration:0.5 options: UIViewAnimationOptionTransitionCrossDissolve completion:^(BOOL finished) {
                weakSelf.window.rootViewController = loginViewController;
                [weakSelf.window makeKeyAndVisible];
            }];
        }
    };
}

- (void)setLoginViewController {
    KKLoginViewController *viewController = [KKLoginViewController viewControllerFromSB];
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];
}

- (void)setChatListViewController {
    KKNavigationController *viewController = [KKNavigationController viewControllerFromSB];
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];
}

#pragma mark - Getter methods

- (NSString*)pushToken {
    return [self.deviceToken pushToken];
}

@end
